package org.example.contestb.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;

import jakarta.servlet.http.HttpServletResponse;
import org.example.contestb.entity.DTO.ToExcelDTO;
import org.example.contestb.entity.Patient;
import org.example.contestb.entity.VO.DetailedPatientVO;
import org.example.contestb.entity.VO.RoughlyPatientVO;
import org.example.contestb.responce.R;
import org.example.contestb.service.PatientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@RestController
@RequestMapping("/patient")
public class PatientController {
    @Autowired
    PatientService patientService;

    @SaCheckLogin
    @GetMapping("/displayRoughly")
    public R displayRoughly(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "5") Integer pageSize
    ){
        RoughlyPatientVO roughlyPatientVO =  patientService.displayRoughly(page,pageSize);
        return R.success(roughlyPatientVO);
    }

    @SaCheckLogin
    @GetMapping("/displayDetailed")
    public R displayDetailed(@RequestParam Integer patientId){
        DetailedPatientVO detailedPatientVO =  patientService.displayDetailed(patientId);
        return R.success(detailedPatientVO);
    }

    @SaCheckLogin
    @GetMapping("/search")
    public R patientSearch(@RequestParam String name){
        List<Patient> list = patientService.patientSearch(name);
        return R.success(list);
    }

    @SaCheckLogin
    @PostMapping("/patientToExcel")
    public ResponseEntity<Resource> downloadExcel(@RequestBody ToExcelDTO toExcelDTO) throws IOException {
        String filePath = patientService.patientToExcel(toExcelDTO);
        // 读取文件
        File file = new File(filePath);

        Resource resource = new InputStreamResource(Files.newInputStream(file.toPath()));

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"");
        headers.add(HttpHeaders.CONTENT_TYPE, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .body(resource);
    }

}
